package com.yanqu.road.server.manger.config;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.mall.MallActivityInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.config.goods.MallWheelResult;
import com.yanqu.road.entity.config.vehicle.VehicleInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.goods.MallRandomGoods;
import com.yanqu.road.entity.player.ReturnData;
import com.yanqu.road.entity.player.UserMallBuyCount;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.recharge.ThirdPartyRechargeOrder;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.logic.bussiness.config.GoodsBussiness;
import com.yanqu.road.logic.bussiness.config.MallBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.*;
import com.yanqu.road.server.manger.activity.assistantcostumemall.AssistantCostumeMallActivityMgr;
import com.yanqu.road.server.manger.activity.orewar.OreWarActivityMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionWarActivityMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.*;

/**
 * 商城管理类
 */
public class MallMgr extends TempMgr {

    private static Map<Integer, MallInfo> mallInfoMap;

    //shopType
    private static Map<Integer, MallRandomGoods> mallRandomGoodsMap;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (MallRandomGoods goods : mallRandomGoodsMap.values()) {
            if (goods.isInsertOption()) {
                GoodsBussiness.addMallRandomGoods(goods);
            } else if (goods.isUpdateOption()) {
                GoodsBussiness.updateMallRandomGoods(goods);
            }
        }
        return true;
    }

    @Override
    public boolean reloadConfig() {
        mallInfoMap = MallBussiness.getMallInfo();

        mallRandomGoodsMap = GoodsBussiness.getMallRandomGoods();

        if (!mallRandomGoodsMap.containsKey(eShopType.BeautySkinMall.getValue())) {
            generateRandomMallInfo(eShopType.BeautySkinMall.getValue(), ConfigMgr.getSkinMallBeautyNum(), false);
        }
        if (!mallRandomGoodsMap.containsKey(eShopType.PatronsSkinMall.getValue())) {
            generateRandomMallInfo(eShopType.PatronsSkinMall.getValue(), ConfigMgr.getSkinMallPatronsNum(), false);
        }
//        if (!mallRandomGoodsMap.containsKey(eShopType.AssistantSkinMall.getValue())) {
//            generateRandomMallInfo(eShopType.AssistantSkinMall.getValue(), ConfigMgr.getSkinMallAssistantNum());
//        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    public static void generateRandomMallInfo(int shopType, int num, boolean force) {
        MallRandomGoods mallRandomGoods = mallRandomGoodsMap.get(shopType);
        if (mallRandomGoods == null) {
            mallRandomGoods = new MallRandomGoods();
            mallRandomGoods.setShopType(shopType);
            setNewMallIdInToMallRandomGoods(mallRandomGoods, shopType, num, force);
            mallRandomGoods.setInsertOption();
            mallRandomGoodsMap.put(shopType, mallRandomGoods);
        } else {
            setNewMallIdInToMallRandomGoods(mallRandomGoods, shopType, num, force);
        }
    }


    /**
     * 设置随机商品到需要随机的商品数据内
     *
     * @param mallRandomGoods
     * @param shopType
     * @param num
     */
    public static void setNewMallIdInToMallRandomGoods(MallRandomGoods mallRandomGoods, int shopType, int num, boolean force) {
        if (mallRandomGoods == null) {
            return;
        }

        boolean refresh = AssistantCostumeMallActivityMgr.refreshRandomGoods(mallRandomGoods, shopType, force);
        if(refresh){
            return;
        }

        if(num == 0){
            num = getNumByShopType(shopType);
        }

        //时间不到，不刷新
        if(!force) {
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();
            if (mallRandomGoods.getLastUpdateTime() >= zeroTime) {
                return;
            }
        }

        //初始皮肤兑换商店
        Map<Integer, MallInfo> goods = new HashMap<>();
        for (MallInfo mallInfo : mallInfoMap.values()) {
            if (shopType == mallInfo.getShopType()) {
                goods.put(mallInfo.getMallId(), mallInfo);
            }
        }
        //权重获取
        List<MallInfo> allMallInfo = new ArrayList<>();
        for (MallInfo mInfo : goods.values()) {
            int weight = (int)MallRechargeConfigMgr.getParamValue(mInfo);
//            int weight = Integer.valueOf(mInfo.getParam());
            for (int i = 0; i < weight; i++) {
                allMallInfo.add(mInfo);
            }
        }
        Set<Integer> mallIdList = new HashSet<>();
        while (goods.size() > 0 && mallIdList.size() < num) {
            int idx = new Random().nextInt(allMallInfo.size());
            if (mallIdList.contains(allMallInfo.get(idx).getMallId())) {
                continue;
            }
            mallIdList.add(allMallInfo.get(idx).getMallId());
        }
        mallRandomGoods.setMallIdList(new ArrayList<>(mallIdList));
        mallRandomGoods.setLastUpdateTime(LocalDateTimeHelper.getZeroTimeTimeStamp());

        getLogger().info("setNewMallIdInToMallRandomGoods type {} ids: {}, force : {}", shopType, StringUtils.listToString(mallRandomGoods.getMallIdList(), ","), force);
    }

    public static Map<Integer, Integer> getRandomMallItemWeigh(int shopType){
        Map<Integer, Integer> result = new HashMap<>();
        List<MallInfo> mallInfoList = AssistantCostumeMallActivityMgr.getMallInfosLimitByServerOpenDays(shopType);
        for (MallInfo mallInfo : mallInfoList) {
            List<Integer> mallItem = StringUtils.stringToIntegerList(mallInfo.getReward(), "=");
            if(mallItem.size() == 2) {
                int old = result.getOrDefault(mallItem.get(0), 0);
                result.put(mallItem.get(0), (int)MallRechargeConfigMgr.getParamValue(mallInfo) + old);
//                result.put(mallItem.get(0), Integer.valueOf(mallInfo.getParam()) + old);
            }
        }
        return result;
    }

    public static MallInfo getMallInfoByMallId(int mallId) {
        if (mallInfoMap.containsKey(mallId)) {
            return mallInfoMap.get(mallId);
        }
        MallInfo mallInfo = MallActivityMgr.getMallInfo(mallId);        //商城活动商品
        if (null != mallInfo) {
            return mallInfo;
        }
        mallInfo = NormalActivityMgr.getActivityMallInfo(mallId);      //普通活动商品
        if (null != mallInfo) {
            return mallInfo;
        }
        mallInfo = CommonActivityMgr.getMallInfo(mallId);              //万能活动商品
        if (null != mallInfo){
            return mallInfo;
        }
        mallInfo = TradeWarActivityMgr.getMallInfo(mallId);
        if(null != mallInfo){
            return mallInfo;
        }
        mallInfo = OreWarActivityMgr.getMallInfo(mallId);
        if(null != mallInfo){
            return mallInfo;
        }
        mallInfo = UnionWarActivityMgr.getActivityMallInfo(mallId);    //群英争霸活动商品
        if(null != mallInfo){
            return mallInfo;
        }
        mallInfo = RelationActivityMgr.getMallInfo(mallId);    //群英争霸活动商品
        if(null != mallInfo){
            return mallInfo;
        }
        return mallInfo;

    }

    private static void checkMallGoodsUpdate() {
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();
        for (MallRandomGoods mallRandomGoods : mallRandomGoodsMap.values()) {
//            if (mallRandomGoods.getShopType() == eShopType.AssistantSkinMall.getValue()) {
//                if (DateHelper.calc2DateTDOADays(new Date(mallRandomGoods.getLastUpdateTime()), new Date()) > ConfigMgr.getSkinMallAssistantUpdateDays()) {
//                    generateRandomMallInfo(mallRandomGoods.getShopType(), getNumByShopType(mallRandomGoods.getShopType()));
//                }
//                continue;
//            }
            if (mallRandomGoods.getLastUpdateTime() < zeroTime) {
                generateRandomMallInfo(mallRandomGoods.getShopType(), getNumByShopType(mallRandomGoods.getShopType()), false);
            }
        }
    }

    public synchronized static MallRandomGoods getMallRandomGoodsByShopType(int shopType) {
        checkMallGoodsUpdate();
        return mallRandomGoodsMap.get(shopType);
    }

    private static int getNumByShopType(int shopType) {
        if (shopType == eShopType.BeautySkinMall.getValue()) {
            return ConfigMgr.getSkinMallBeautyNum();
        }
        if (shopType == eShopType.PatronsSkinMall.getValue()) {
            return ConfigMgr.getSkinMallPatronsNum();
        }
//        if (shopType == eShopType.AssistantSkinMall.getValue()) {
//            return ConfigMgr.getSkinMallAssistantNum();
//        }
        return 0;
    }


    public static Property getPriceConsume(int count, int oldBuyCount, MallInfo mallInfo) {
        Property consume = new Property();
        int mallBuyCount = oldBuyCount;
        Property priceProperty = PropertyHelper.parseStringToProperty(mallInfo.getPrice());
        if (null != priceProperty) {
            for (Map.Entry<Integer, BigInteger> entry : priceProperty.getGoods().entrySet()) {
                BigInteger totalPrice = BigInteger.ZERO;
                for (int i = 0; i < count; i++) {
                    //配置的价格
                    BigInteger price = entry.getValue();
                    //2023-11-30 折扣处理-需求更改，服务端无需处理
//                    price = getDiscountPriceConsume(price, mallInfo.getDiscount());
                    //加上递增的价格
                    price = price.add(BigInteger.valueOf(mallInfo.getPriceAdd() * mallBuyCount));
                    totalPrice = totalPrice.add(price);
                    if (mallInfo.getPriceAdd() > 0 || -1 != mallInfo.getLimitBuyCount()) {
                        mallBuyCount++;
                    }
                }
                consume.addProperty(entry.getKey(), totalPrice);
            }
        }
        return consume;
    }

    /**
     * 折扣
     * @param price
     * @param discountRate
     * @return
     */
    private static BigInteger getDiscountPriceConsume(BigInteger price, int discountRate) {
        if (discountRate == 0) {
            return price;
        }
        BigDecimal dis = BigDecimal.valueOf(discountRate).divide(BigDecimal.valueOf(1000));
        BigDecimal priceBig = (BigDecimal.valueOf(price.intValue()).multiply(dis)).setScale(0, RoundingMode.UP);
        return BigInteger.valueOf(priceBig.intValue());
    }

    public static Property getGoldTokenConsume(int count, int oldBuyCount, MallInfo mallInfo) {
        Property consume = new Property();
        int mallBuyCount = oldBuyCount;
        int vipExp = (int)MallRechargeConfigMgr.getParamValue(mallInfo);
//        int vipExp = StringUtils.string2intSafe(mallInfo.getParam(), 0);
        Property priceProperty = new Property(eItemId.GOLD_TOKEN.getValue(), BigInteger.valueOf(vipExp));
        if (mallInfo.getPriceAdd() > 0 || -1 != mallInfo.getLimitBuyCount()) {
            for (Map.Entry<Integer, BigInteger> entry : priceProperty.getGoods().entrySet()) {
                BigInteger totalPrice = BigInteger.ZERO;
                for (int i = 0; i < count; i++) {
                    BigInteger price = entry.getValue().add(BigInteger.valueOf(mallInfo.getPriceAdd() * mallBuyCount));
                    totalPrice = totalPrice.add(price);
                    mallBuyCount++;
                }
                consume.addProperty(entry.getKey(), totalPrice);
            }
        }else {
            consume = priceProperty;
        }
        return consume;
    }

    public static ReturnData getAssistantPriceConsume(int count, int oldBuyCount, MallInfo mallInfo, GamePlayer player) {
        Property consume = new Property();
        int mallBuyCount = oldBuyCount;
        int realCount = 0;
        CurrencyModule module = player.getModule(CurrencyModule.class);
        Property priceProperty = PropertyHelper.parseStringToProperty(mallInfo.getPrice());
        if (null != priceProperty) {
            for (int i = 0; i < count; i++) {
                Property compareProperty = new Property();
                Property addProperty = new Property();
                for (Map.Entry<Integer, BigInteger> entry : priceProperty.getGoods().entrySet()) {
                    BigInteger price = entry.getValue().add(BigInteger.valueOf(mallInfo.getPriceAdd() * mallBuyCount));
                    addProperty.addProperty(new Property(entry.getKey(), price));
                    compareProperty.addProperty(consume);
                    compareProperty.addProperty(addProperty);
                }
                if (module.currencyIsEnough(compareProperty)) {
                    consume.addProperty(addProperty);
                    realCount++;
                    if (mallInfo.getPriceAdd() > 0 || -1 != mallInfo.getLimitBuyCount()) {
                        mallBuyCount++;
                    }
                } else {
                    return new ReturnData(0, realCount + "", PropertyHelper.parsePropertyToString(consume));
                }
            }
        }
        return new ReturnData(0, realCount + "", PropertyHelper.parsePropertyToString(consume));
    }
    public static boolean isVehicleCombActivityLimit(MallInfo mallInfo){
        Property property = PropertyHelper.parseStringToProperty(mallInfo.getReward());
        for(Map.Entry<Integer, BigInteger> dataEntry : property.getGoods().entrySet()){
            if(GoodsMgr.isVehicleGoods(dataEntry.getKey())){
                VehicleInfo vehicleInfo = VehicleMgr.getVehicleInfo(dataEntry.getKey());
                if(vehicleInfo.getCombId() > 0){//是组合门客，需要在活动中才能兑换
                    List<ActivityInfo> vehicleCombActivityList = NormalActivityMgr.getVehicleCombActivityInfoList();
                    boolean isFind = false;
                    for(ActivityInfo activityInfo : vehicleCombActivityList){
                        List<ActivityConditionInfo> activityConditionInfoList = NormalActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId());
                        if(null != activityConditionInfoList) {
                            for (ActivityConditionInfo activityConditionInfo : activityConditionInfoList) {
                                if (activityConditionInfo.getParamList().get(0).intValue() == vehicleInfo.getCombId()) {
                                    isFind = true;
                                    break;
                                }
                            }
                        }
                        if(isFind){
                            break;
                        }
                    }
                    if(!isFind){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 是否已知限购类商品（门客、美女）
     */
    public static boolean isLimitBuyGoods(GamePlayer player, MallInfo mallInfo) {
        for (Map.Entry<Integer, BigInteger> dataEntry : mallInfo.getRewardProp().getGoods().entrySet()) {
            if (GoodsMgr.isPatronsGoods(dataEntry.getKey()) && player.getModule(PatronsModule.class).getUserPatrons(dataEntry.getKey()) != null) {//门客不允许重复购买
                return true;
            }
            if (GoodsMgr.isPatronsGoods(dataEntry.getKey()) && player.getModule(PatronsModule.class).checkPatronsConflict(dataEntry.getKey()) != null) {//互斥门客不允许重复购买
                return true;
            }
            if (GoodsMgr.isBeautyGoods(dataEntry.getKey()) && player.getModule(BeautyModule.class).getUserBeauty(dataEntry.getKey()) != null) {//美女不允许重复购买
                return true;
            }
        }
        return false;
    }

    /**
     * 商会条件限购
     */
    public static boolean isUnionLimit(GamePlayer player, MallInfo mallInfo) {
        if (mallInfo.getShopType() == eShopType.UnionMall.getValue()) {
            int limitUnionLv = (int)MallRechargeConfigMgr.getParamValue(mallInfo);
//            int limitUnionLv = Integer.parseInt(mallInfo.getParam());
            String unionUid = player.getUserInfo().getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid)) {
                return true;
            }
            UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if (null == unionInfo) {
                return true;
            }
            return UnionConfigMgr.getUnionLv(unionInfo.getExperience()) < limitUnionLv;
        }
        return false;
    }

    public static boolean isRechargeLimitBuy(MallInfo mallInfo, String orderNo, List<RechargeOrder> rechargeOrderList,
                                             List<ThirdPartyRechargeOrder> thirdPartyOrderList, boolean isThirdParty) {
        if (mallInfo != null) {
            int buyUpLimit = mallInfo.getLimitBuyCount();
            if (buyUpLimit == -1) {
                return false;
            }
            int buyTimes;
            int limitBuyType = mallInfo.getLimitBuyType();
            if (eLimitBuyType.DAILY.getValue() == limitBuyType) {
                buyTimes = getDayBuyTimes(mallInfo, orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty);
            } else if (eLimitBuyType.WEEK.getValue() == limitBuyType) {
                buyTimes = getWeekBuyTimes(mallInfo, orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty);
            } else if (eLimitBuyType.MONTH.getValue() == limitBuyType) {
                buyTimes = getMonthBuyTimes(mallInfo, orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty);
            } else if (eLimitBuyType.FOREVER.getValue() == limitBuyType) {
                buyTimes = getForeverBuyTimes(mallInfo, orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty);
            } else {
                buyTimes = 0;
            }
            return buyTimes >= buyUpLimit;
        }
        return false;
    }

    private static int getForeverBuyTimes(MallInfo mallInfo, String orderNo, List<RechargeOrder> rechargeOrderList,
                                          List<ThirdPartyRechargeOrder> thirdPartyOrderList, boolean isThirdParty) {
        int buyTimes = 0;
        for (RechargeOrder rechargeOrder : rechargeOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                ) {
                    if (isThirdParty) {
                        buyTimes++;
                    } else {
                        if (!rechargeOrder.getOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    }
                }
            }
        }
        for (ThirdPartyRechargeOrder rechargeOrder : thirdPartyOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                ) {
                    if (isThirdParty) {
                        if (!rechargeOrder.getPlatformOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    } else {
                        buyTimes++;
                    }
                }
            }
        }
        return buyTimes;
    }

    private static int getMonthBuyTimes(MallInfo mallInfo, String orderNo, List<RechargeOrder> rechargeOrderList,
                                        List<ThirdPartyRechargeOrder> thirdPartyOrderList, boolean isThirdParty) {
        int buyTimes = 0;
        for (RechargeOrder rechargeOrder : rechargeOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                long createTime = rechargeOrder.getCreateTime().getTime();
                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                        && DateHelper.isSameMonth(createTime)) {
                    if (isThirdParty) {
                        buyTimes++;
                    } else {
                        if (!rechargeOrder.getOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    }
                }
            }
        }
        for (ThirdPartyRechargeOrder rechargeOrder : thirdPartyOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                long createTime = rechargeOrder.getCreateTime().getTime();
                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                        && DateHelper.isSameMonth(createTime)) {
                    if (isThirdParty) {
                        if (!rechargeOrder.getPlatformOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    } else {
                        buyTimes++;
                    }
                }
            }
        }
        return buyTimes;
    }

    private static int getWeekBuyTimes(MallInfo mallInfo, String orderNo, List<RechargeOrder> rechargeOrderList,
                                       List<ThirdPartyRechargeOrder> thirdPartyOrderList, boolean isThirdParty) {
        int buyTimes = 0;
        for (RechargeOrder rechargeOrder : rechargeOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                long createTime = rechargeOrder.getCreateTime().getTime();
                Date createDate = new Date(createTime);

                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                        && DateHelper.isSameWeek(createDate, new Date())) {
                    if (isThirdParty) {
                        buyTimes++;
                    } else {
                        if (!rechargeOrder.getOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    }
                }
            }
        }
        for (ThirdPartyRechargeOrder rechargeOrder : thirdPartyOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                long createTime = rechargeOrder.getCreateTime().getTime();
                Date createDate = new Date(createTime);

                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                        && DateHelper.isSameWeek(createDate, new Date())) {
                    if (isThirdParty) {
                        if (!rechargeOrder.getPlatformOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    } else {
                        buyTimes++;
                    }
                }
            }
        }
        return buyTimes;
    }

    private static int getDayBuyTimes(MallInfo mallInfo, String orderNo, List<RechargeOrder> rechargeOrderList,
                                      List<ThirdPartyRechargeOrder> thirdPartyOrderList, boolean isThirdParty) {
        int buyTimes = 0;
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();
        for (RechargeOrder rechargeOrder : rechargeOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                long createTime = rechargeOrder.getCreateTime().getTime();
                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                        && createTime >= zeroTime) {
                    if (isThirdParty) {
                        buyTimes++;
                    } else {
                        if (!rechargeOrder.getOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    }
                }
            }
        }
        for (ThirdPartyRechargeOrder rechargeOrder : thirdPartyOrderList) {
            if (rechargeOrder != null && rechargeOrder.getCreateTime() != null) {
                long createTime = rechargeOrder.getCreateTime().getTime();
                if (rechargeOrder.getMallId() == mallInfo.getMallId()
                        && rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)
                        && !rechargeOrder.isRepeatBuy()
                        && createTime >= zeroTime) {
                    if (isThirdParty) {
                        if (!rechargeOrder.getPlatformOrderNo().equals(orderNo)) {
                            buyTimes++;
                        }
                    } else {
                        buyTimes++;
                    }
                }
            }
        }
        return buyTimes;
    }

    /**
     * 获取商品名称
     */
    public static String getMallName(MallInfo mallInfo, String language) {
        if (null == mallInfo) {
            return "";
        }
        if (mallInfo.getActivityId() > 0) {
            return ServerLanguageMgr.getContent(mallInfo.getMallName(), language);
        } else {
            return MultipleLanguageMgr.getContent(mallInfo.getMallName(), language);
        }
    }

    public static List<MallInfo> getMallInfoList(int category) {
        List<MallInfo> dataList = new ArrayList<>();
        for (MallInfo mallInfo : mallInfoMap.values()) {
            if (mallInfo.getCategory() == category) {
                dataList.add(mallInfo);
            }
        }
        return dataList;
    }

    public static List<MallInfo> getMallInfoListByShopType(int shopType) {
        List<MallInfo> dataList = new ArrayList<>();
        for (MallInfo mallInfo : mallInfoMap.values()) {
            if (mallInfo.getShopType() == shopType) {
                dataList.add(mallInfo);
            }
        }
        return dataList;
    }

    /**
     * 商品限购重置
     */
    public static boolean isMallBuyCountReset(long zeroTime, UserMallBuyCount userMallBuyCount, MallInfo mallInfo) {
        boolean isReset = false;
        if (eLimitBuyType.DAILY.getValue() == mallInfo.getLimitBuyType()) {
            if (userMallBuyCount.getLastUpdateTime() < zeroTime) {
                isReset = true;
            }
        } else if (eLimitBuyType.WEEK.getValue() == mallInfo.getLimitBuyType()) {
            if (!DateHelper.isSameWeek(userMallBuyCount.getLastUpdateTime(), zeroTime)) {
                isReset = true;
            }
        } else if (eLimitBuyType.MONTH.getValue() == mallInfo.getLimitBuyType()) {
            if (!DateHelper.isSameMonth(userMallBuyCount.getLastUpdateTime(), zeroTime)) {
                isReset = true;
            }
        } else if (eLimitBuyType.FOREVER.getValue() == mallInfo.getLimitBuyType()) {
            isReset = false;
        }
        return isReset;
    }

    public static boolean isPalaceMallLimit(int titleType, MallInfo mallInfo) {
        if (mallInfo.getShopType() == eShopType.PalaceExchangeMall.getValue()) {
            int limitTitleType = (int)MallRechargeConfigMgr.getParamValue(mallInfo);
//            int limitTitleType = StringUtils.string2intSafe(mallInfo.getParam(), 0);
            if(limitTitleType > 0) {//title值越小其实是越大，反过来了
                return titleType <= 0 || titleType > limitTitleType;
            }
        }
        return false;
    }

    /**
    * 描述：返通宝
    * 作者：zrq
    * 时间：2022/11/17
    * 参数：

    * 返回值：
    **/
    public static void returnGoldToken(GamePlayer player, MallInfo mallInfo, int couponGoodsId) {
        if(null == mallInfo){
            return;
        }
        int addVipExp = (int)MallRechargeConfigMgr.getParamValue(mallInfo);
//        int addVipExp = StringUtils.string2intSafe(mallInfo.getParam(), 0);
        if(couponGoodsId > 0){
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(couponGoodsId);
            if(null != goodsInfo){
                int param4 = goodsInfo.getParamList().get(3).intValue();
                addVipExp = addVipExp - param4;
            }
        }
        if(addVipExp > 0) {
            String language = player.getLanguage();
            String mailTitle;
            String mailContent;
            if(couponGoodsId > 0){
                mailTitle = MultipleLanguageMgr.getContent(MailManager.MALL_VOUCHER_REPEAT_BUY_TITLE, language);
                mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.MALL_VOUCHER_REPEAT_BUY_CONTENT, language),
                        getMallName(mallInfo, language));
            }else {
                mailTitle = MultipleLanguageMgr.getContent(MailManager.MALL_REPEAT_BUY_TITLE, language);
                mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.MALL_REPEAT_BUY_CONTENT, language),
                        getMallName(mallInfo, language));
            }
            MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(),
                    PropertyHelper.parseGoodsToString(eItemId.GOLD_TOKEN.getValue(), BigInteger.valueOf(addVipExp)), mailContent, mailTitle);
        }
    }

    /**
    * 描述：活动过期返通宝
    * 作者：zrq
    * 时间：2022/11/17
    * 参数：

    * 返回值：
    **/
    public static void mallNoFindReturnGoldToken(GamePlayer player, String mallName, Date buyTime, int addVipExp) {
        String language = player.getLanguage();
        String mailTitle = MultipleLanguageMgr.getContent(MailManager.MALL_BUY_OVER_TIME_TITLE, language);
        String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.MALL_BUY_OVER_TIME_CONTENT, language),
                DateHelper.getCurrentDateTimeString(buyTime.getTime()), mallName);
        MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(),
                PropertyHelper.parseGoodsToString(eItemId.GOLD_TOKEN.getValue(), BigInteger.valueOf(addVipExp)), mailContent, mailTitle);
    }

    /**
    * 描述：是否订阅商品
    * 作者：zrq
    * 时间：2023/3/22
    * 参数：

    * 返回值：
    **/
    public static boolean isSubscribeMall(int mallId){
        if(mallId == GameConfig.SUBSCRIBE_WEEK_CARD_MALL_ID){
            return true;
        }
        return false;
    }
}
